﻿
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace JinianNet.KuaiBlog.SQLServerDAL
{
    /// <summary>
    /// 数据访问类:Posts
    /// </summary>
    public partial class Post : BaseDAL
    {
        public Post()
        { }


        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(JinianNet.KuaiBlog.Entity.Post model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into be_Posts(");
            strSql.Append("BlogId,PostId,Title,Description,PostContent,DateCreated,DateModified,Author,IsPublished,IsCommentEnabled,Raters,Rating,Slug,IsDeleted)");
            strSql.Append(" values (");
            strSql.Append("@BlogId,@PostId,@Title,@Description,@PostContent,@DateCreated,@DateModified,@Author,@IsPublished,@IsCommentEnabled,@Raters,@Rating,@Slug,@IsDeleted)");
            strSql.Append(";select @@IdENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@BlogId", SqlDbType.UniqueIdentifier,16),
					new SqlParameter("@PostId", SqlDbType.UniqueIdentifier,16),
					new SqlParameter("@Title", SqlDbType.NVarChar,255),
					new SqlParameter("@Description", SqlDbType.NVarChar,-1),
					new SqlParameter("@PostContent", SqlDbType.NVarChar,-1),
					new SqlParameter("@DateCreated", SqlDbType.DateTime),
					new SqlParameter("@DateModified", SqlDbType.DateTime),
					new SqlParameter("@Author", SqlDbType.NVarChar,50),
					new SqlParameter("@IsPublished", SqlDbType.Bit,1),
					new SqlParameter("@IsCommentEnabled", SqlDbType.Bit,1),
					new SqlParameter("@Raters", SqlDbType.Int,4),
					new SqlParameter("@Rating", SqlDbType.Real,4),
					new SqlParameter("@Slug", SqlDbType.NVarChar,255),
					new SqlParameter("@IsDeleted", SqlDbType.Bit,1)};
            parameters[0].Value = Guid.NewGuid();
            parameters[1].Value = Guid.NewGuid();
            parameters[2].Value = model.Title;
            parameters[3].Value = model.Description;
            parameters[4].Value = model.PostContent;
            parameters[5].Value = model.DateCreated;
            parameters[6].Value = model.DateModified;
            parameters[7].Value = model.Author;
            parameters[8].Value = model.IsPublished;
            parameters[9].Value = model.IsCommentEnabled;
            parameters[10].Value = model.Raters;
            parameters[11].Value = model.Rating;
            parameters[12].Value = model.Slug;
            parameters[13].Value = model.IsDeleted;

            object obj = Helper.ExecuteScalar(CommandType.Text, strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(JinianNet.KuaiBlog.Entity.Post model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update be_Posts set ");
            strSql.Append("BlogId=@BlogId,");
            strSql.Append("PostId=@PostId,");
            strSql.Append("Title=@Title,");
            strSql.Append("Description=@Description,");
            strSql.Append("PostContent=@PostContent,");
            strSql.Append("DateCreated=@DateCreated,");
            strSql.Append("DateModified=@DateModified,");
            strSql.Append("Author=@Author,");
            strSql.Append("IsPublished=@IsPublished,");
            strSql.Append("IsCommentEnabled=@IsCommentEnabled,");
            strSql.Append("Raters=@Raters,");
            strSql.Append("Rating=@Rating,");
            strSql.Append("Slug=@Slug,");
            strSql.Append("IsDeleted=@IsDeleted");
            strSql.Append(" where PostRowId=@PostRowId");
            SqlParameter[] parameters = {
					new SqlParameter("@BlogId", SqlDbType.UniqueIdentifier,16),
					new SqlParameter("@PostId", SqlDbType.UniqueIdentifier,16),
					new SqlParameter("@Title", SqlDbType.NVarChar,255),
					new SqlParameter("@Description", SqlDbType.NVarChar,-1),
					new SqlParameter("@PostContent", SqlDbType.NVarChar,-1),
					new SqlParameter("@DateCreated", SqlDbType.DateTime),
					new SqlParameter("@DateModified", SqlDbType.DateTime),
					new SqlParameter("@Author", SqlDbType.NVarChar,50),
					new SqlParameter("@IsPublished", SqlDbType.Bit,1),
					new SqlParameter("@IsCommentEnabled", SqlDbType.Bit,1),
					new SqlParameter("@Raters", SqlDbType.Int,4),
					new SqlParameter("@Rating", SqlDbType.Real,4),
					new SqlParameter("@Slug", SqlDbType.NVarChar,255),
					new SqlParameter("@IsDeleted", SqlDbType.Bit,1),
					new SqlParameter("@PostRowId", SqlDbType.Int,4)};
            parameters[0].Value = model.BlogId;
            parameters[1].Value = model.PostId;
            parameters[2].Value = model.Title;
            parameters[3].Value = model.Description;
            parameters[4].Value = model.PostContent;
            parameters[5].Value = model.DateCreated;
            parameters[6].Value = model.DateModified;
            parameters[7].Value = model.Author;
            parameters[8].Value = model.IsPublished;
            parameters[9].Value = model.IsCommentEnabled;
            parameters[10].Value = model.Raters;
            parameters[11].Value = model.Rating;
            parameters[12].Value = model.Slug;
            parameters[13].Value = model.IsDeleted;
            parameters[14].Value = model.PostRowId;

            int rows = Helper.ExecuteNonQuery(CommandType.Text, strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int PostRowId)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from be_Posts ");
            strSql.Append(" where PostRowId=@PostRowId");
            SqlParameter[] parameters = {
					new SqlParameter("@PostRowId", SqlDbType.Int,4)
			};
            parameters[0].Value = PostRowId;

            int rows = Helper.ExecuteNonQuery(CommandType.Text, strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string PostRowIdlist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from be_Posts ");
            strSql.Append(" where PostRowId in (" + PostRowIdlist + ")  ");
            int rows = Helper.ExecuteNonQuery(CommandType.Text, strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public JinianNet.KuaiBlog.Entity.Post GetItem(string slug)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 PostRowId,BlogId,PostId,Title,Description,PostContent,DateCreated,DateModified,Author,IsPublished,IsCommentEnabled,Raters,Rating,Slug,IsDeleted from be_Posts ");
            strSql.Append(" where Slug=@Slug");
            SqlParameter[] parameters = {
					new SqlParameter("@slug", SqlDbType.NVarChar,255)
			};
            parameters[0].Value = slug;

            JinianNet.KuaiBlog.Entity.Post model = new JinianNet.KuaiBlog.Entity.Post();
            using (System.Data.Common.DbDataReader dr = Helper.ExecuteReader(CommandType.Text, strSql.ToString(), parameters))
            {
                if (dr.Read())
                {
                    return GetItem(dr);
                }
                else
                {
                    return null;
                }
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        private JinianNet.KuaiBlog.Entity.Post GetItem(System.Data.Common.DbDataReader row)
        {
            JinianNet.KuaiBlog.Entity.Post model = new JinianNet.KuaiBlog.Entity.Post();
            if (row != null)
            {
                if (row["PostRowId"] != null && row["PostRowId"].ToString() != "")
                {
                    model.PostRowId = int.Parse(row["PostRowId"].ToString());
                }
                if (row["BlogId"] != null && row["BlogId"].ToString() != "")
                {
                    model.BlogId = new Guid(row["BlogId"].ToString());
                }
                if (row["PostId"] != null && row["PostId"].ToString() != "")
                {
                    model.PostId = new Guid(row["PostId"].ToString());
                }
                if (row["Title"] != null)
                {
                    model.Title = row["Title"].ToString();
                }
                if (row["Description"] != null)
                {
                    model.Description = row["Description"].ToString();
                }
                if (row["PostContent"] != null)
                {
                    model.PostContent = row["PostContent"].ToString();
                }
                if (row["DateCreated"] != null && row["DateCreated"].ToString() != "")
                {
                    model.DateCreated = DateTime.Parse(row["DateCreated"].ToString());
                }
                if (row["DateModified"] != null && row["DateModified"].ToString() != "")
                {
                    model.DateModified = DateTime.Parse(row["DateModified"].ToString());
                }
                if (row["Author"] != null)
                {
                    model.Author = row["Author"].ToString();
                }
                if (row["IsPublished"] != null && row["IsPublished"].ToString() != "")
                {
                    if ((row["IsPublished"].ToString() == "1") || (row["IsPublished"].ToString().ToLower() == "true"))
                    {
                        model.IsPublished = true;
                    }
                    else
                    {
                        model.IsPublished = false;
                    }
                }
                if (row["IsCommentEnabled"] != null && row["IsCommentEnabled"].ToString() != "")
                {
                    if ((row["IsCommentEnabled"].ToString() == "1") || (row["IsCommentEnabled"].ToString().ToLower() == "true"))
                    {
                        model.IsCommentEnabled = true;
                    }
                    else
                    {
                        model.IsCommentEnabled = false;
                    }
                }
                if (row["Raters"] != null && row["Raters"].ToString() != "")
                {
                    model.Raters = int.Parse(row["Raters"].ToString());
                }
                if (row["Rating"] != null && row["Rating"].ToString() != "")
                {
                    model.Rating = decimal.Parse(row["Rating"].ToString());
                }
                if (row["Slug"] != null)
                {
                    model.Slug = row["Slug"].ToString();
                }
                if (row["IsDeleted"] != null && row["IsDeleted"].ToString() != "")
                {
                    if ((row["IsDeleted"].ToString() == "1") || (row["IsDeleted"].ToString().ToLower() == "true"))
                    {
                        model.IsDeleted = true;
                    }
                    else
                    {
                        model.IsDeleted = false;
                    }
                }
            }
            return model;
        }



        /// <summary>
        /// 获得数据列表
        /// </summary>
        public IList<Entity.Post> GetList(Guid blogId, string slug, string tag, string currentUser, int pageIndex, int pageSize,out int pageCount)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("be_Posts where IsDeleted=0");

            List<SqlParameter> parameters = new List<SqlParameter>();

            if (!string.IsNullOrEmpty(currentUser))
            {
                strSql.Append(" and (IsPublished=1 or Author=@User)");
                parameters.Add(new SqlParameter("@User", SqlDbType.NVarChar, 50));
                parameters[parameters.Count - 1].Value = currentUser;
            }
            else
            {
                strSql.Append(" and IsPublished=1");
            }
            
            if (blogId!=null)
			{
                strSql.Append(" and BlogId=@BlogId");
                parameters.Add(new SqlParameter("@BlogId", SqlDbType.UniqueIdentifier,16));
                parameters[parameters.Count - 1].Value = blogId;
			}

            if (!string.IsNullOrEmpty(slug))
			{
                strSql.Append(" and exists(select * from be_PostCategory where be_PostCategory.PostID=be_Posts.PostID and CategoryID=@CategoryID)");
                parameters.Add(new SqlParameter("@CategoryID", SqlDbType.UniqueIdentifier));
                parameters[parameters.Count - 1].Value =new Guid((Helper.ExecuteScalar("select CategoryID from be_Categories where Slug={0}",slug) ?? "").ToString());
			}


            if (!string.IsNullOrEmpty(tag))
            {
                strSql.Append(" and exists(select * from be_PostTag where be_PostTag.PostID=be_Posts.PostID and Tag=@Tag)");
                parameters.Add(new SqlParameter("@Tag", SqlDbType.NVarChar, 255));
                parameters[parameters.Count - 1].Value = tag;
            }

            List<Entity.Post> list = new List<Entity.Post>();

            int recordCount;
            using(System.Data.Common.DbDataReader dr = Helper.ExecuteReaderPage("PostRowId,BlogId,PostId,Title,Description,PostContent,DateCreated,DateModified,Author,IsPublished,IsCommentEnabled,Raters,Rating,Slug,IsDeleted", strSql.ToString(), "PostRowId", "order by DateCreated desc",pageIndex,pageSize,out recordCount,out pageCount, parameters.ToArray()))
            {
                while(dr.Read())
                {
                    list.Add(GetItem(dr));
                }
            }

            return list;
		}



        /// <summary>
        /// 获得数据列表
        /// </summary>
        public IList<Entity.Post> GetList(Guid blogId, string slug, int pageIndex, int pageSize, out int pageCount)
        {
            return GetList(blogId, slug, null,null, pageIndex, pageSize, out pageCount);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public IList<Entity.Post> GetList(Guid blogId, int pageIndex, int pageSize, out int pageCount)
        {
            return GetList(blogId, null, null,null, pageIndex, pageSize, out pageCount);
        }


        /// <summary>
        /// 获得数据列表
        /// </summary>
        public IList<Entity.Post> GetList(Guid blogId,DateTime date)
        {
            List<Entity.Post> list = new List<Entity.Post>();

            using (System.Data.Common.DbDataReader dr = Helper.ExecuteReader("select PostRowId,BlogId,PostId,Title,Description,PostContent,DateCreated,DateModified,Author,IsPublished,IsCommentEnabled,Raters,Rating,Slug,IsDeleted from be_Posts where IsDeleted=0 and IsPublished=1 and DateCreated be"))
            {
                while (dr.Read())
                {
                    list.Add(GetItem(dr));
                }
            }

            return list;
        }
    }
}

